<template>
  <div>
    <div class="email-customer">
      <!--顶部切换类型-->
      <ul class="top-menu">
        <li :class="{active:currentFrag==-1}" @click="toggle(-1)">全部邮件</li>
        <li :class="{active:currentFrag==0}" @click="toggle(0)">发送的</li>
        <li :class="{active:currentFrag==1}" @click="toggle(1)">接收的</li>
        <div class="line" :style="{left:Left}"></div>
      </ul>
      <!-- 列表数据展示-->
      <div class="list-table" v-loading="loading">
        <!--内容 -->
        <div class="detail" :style="{maxHeight:$height-270+'px',minHeight:total==0?'auto':'300px'}">
          <div v-for="item,i in data" :key="i">
            <h1 class="title-table" v-show="item.total>0">{{item.title}}({{item.total}})</h1>
            <table class="table-detail">
              <tbody>
              <tr v-for="itemSon,i in item.list" :key="i" :class="{'active':itemSon.readStatus==1}">
                <td style="width: 30px;text-align: center">
                  <!--是否建档-->
                  <img v-if="itemSon.emailCustomerVO.type ==0" title="陌生人"
                       src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                       alt="陌生人">
                  <img v-else-if="itemSon.emailCustomerVO.type ==4" title="公海客户"
                       src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                       alt="公海客户">
                  <img v-else-if="itemSon.emailCustomerVO.type ==2" v-else title="同事建档客户"
                       src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                       alt="同事建档客户">
                  <img v-else-if="itemSon.emailCustomerVO.type ==3" v-else title="共享客户"
                       src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                       alt="共享客户">
                  <img v-else title="建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                       class="delivery-img" alt="建档客户">
                </td>
                <td style="width: 20px;text-align: center;padding-right: 10px">
                  <img v-if="itemSon.emailType==1" class="icon-frag"
                       src="../../../../public/img/email/icon/icon-get.png" alt="" title="收件">
                  <img v-else class="icon-frag" src="../../../../public/img/email/icon/icon-put.png" alt="" title="发送">
                </td>
                <td width="270px" @click="toDetail(itemSon)"
                    :title="filterEmail(itemSon,1)">
                  <span class="more" style="width: 260px;padding-right:10px;" v-html="filterEmail(itemSon,0)"></span>
                </td>
                <td :title="itemSon.emailSubject" @click="toDetail(itemSon)">
                  <span class="more" style="max-width: 320px">
                      <!--0.阿里巴巴询盘-->
                    <img v-show="itemSon.alibabaInquiry"  title="阿里巴巴询盘邮件" src="../../../../public/img/email/icon/alibaba.png"
                         class="alibaba" alt="建档客户">
                    <!--1.紧急图标 -->
                     <img v-if="parseInt(itemSon.emaileDelivery)==2" title="紧急邮件"
                          src="../../../../public/img/email/icon/icon-emps.png" class="delivery-img" alt="紧急邮件">
                    <!--2.是否回复-->
                      <img v-if="parseInt(itemSon.emailReply)==1" title="已回复"
                           src="../../../../public/img/email/icon/icon-replay.png" alt="" class="delivery-img">
                    {{itemSon.emailSubject}}
                  </span>
                </td>
                <td style="width: 200px">
                  <el-tag closable
                          v-for="itemElse in itemSon.emailLabelList"
                          :key="itemElse.labelName" :color="itemElse.labelColor"
                          @close="handleClose(itemElse.temailLabelId)">
                    {{itemElse.labelName}}
                  </el-tag>
                </td>
                <td width="150px" :title="itemSon.sendTime" @click="toDetail(itemSon)">
                  <span class="time">{{itemSon.sendTime}}</span>
                </td>
                <td width="90px" class="make-td" >
                  <!-- 待办邮件-->
                  <el-tooltip placement="top" v-if="itemSon.finish==1">
                    <div slot="content">待处理事件:<br/>{{itemSon.processTime}}</div>
                    <img v-show="itemSon.emailType==1" src="../../../../public/img/email/icon/icon-dealed.png"
                         @click="toComplete(itemSon.temailInfoId)" class="delivery-img" alt="待办邮件">
                  </el-tooltip>
                  <img v-else  src="../../../../public/img/email/icon/icon-deal.png"
                       @click="toTimeDeal(itemSon.temailInfoId,itemSon.processTime)"
                       title="标记为待办邮件" class="delivery-img" alt="标记为待办邮件">
                  <span v-show="itemSon.emailType==1">
                    <img v-if="parseInt(itemSon.fixed)==0" src="../../../../public/img/email/icon/icon-fix.png"
                         @click="fixedTop(itemSon.temailInfoId,1)"
                         title="固定邮件" class="delivery-img" alt="固定邮件">
                  <img v-else src="../../../../public/img/email/icon/icon-fixed.png"
                       @click="fixedTop(itemSon.temailInfoId,0)"
                       title="取消固定" class="delivery-img" alt="取消固定">
                  </span>
                  <img src="../../../../public/img/email/icon/icon-del.png" @click="delEmail(itemSon.temailInfoId)"
                       title="删除邮件" class="delivery-img" alt="删除邮件">
                  <!-- 附件-->
                  <img v-show="itemSon.attachmentNumber>0" src="../../../../public/img/email/icon/icon-file.png"
                       title="邮件附件" class="delivery-img" alt="邮件附件">
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="empty" v-show="total==0&&!loading">
        <img src="../../../../public/img/empty.png" alt="">
      </div>
      <el-pagination class="fixed"
                     background align="right"
                     @current-change="handleCurrent"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!-- 时间选择-->
    <TimeDialog ref="timeDialog" @getData="getData"></TimeDialog>
  </div>
</template>
<script>
    import TimeDialog from "@/components/mail/dialog/TimeDialog"
    import {mapState} from 'vuex'
    import {getHour, getNextDate, getDate, getNext, getToady, getYesterday, getNowWeek, getNowMonth,getDiffList} from "@/util/util"
    import {delEmail, labelEmail, delLabel, nextEmail, completeEmail, fixTop} from "@/api/mail/make"
    import {relationEmail} from "@/api/mail/write";

    export default {
        name: "EmailList",
        components: {TimeDialog},
        props: ['id','name'],
        data() {
            return {
                isFixed: 0,
                dialogVisible: false,
                theEmail: '',
                total: 0,
                currentPage: 1,
                showHeader: false,
                checked: false,
                searchContent: '',
                data: [],
                list: [],
                size: 20,
                targetLabel: '',
                targetRemove: '',
                tEmailInfoIds: [],//所选邮件列表
                dialogTime: false,
                emailList: [],
                targetTime: '',
                todayTime: '',
                nextWeek: '',
                nextTime: '',
                userId: '',
                nextEmail: '',
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                listAll: [],
                archiveFolderId: '',
                //新增
                moveArchiveFolderId: '',
                emailSubject: '',
                loading: false,
                isRebound: false,
                currentFrag: -1,
                Left: '25px',
                targetName:''
            }
        },
        computed: {
            ...mapState(['common']),
        },
        watch: {
            dialogVisible(val) {
                if (!val) {
                    this.targetTime = ''
                }
            }
        },
        mounted() {
            this.getData();
            this.todayTime = getHour();
            this.nextWeek = getNextDate();
            if (this.name == 'emailListTab') {//收件箱
                this.targetName = 'SET_EMAILLISTTAB'
            } else if (this.name == 'emailListUnreadTab') {//未读信箱
                this.targetName = 'SET_EMAILLISTUNREADTAB'
            } else if (this.name == 'emailListOutTab') {//已发送箱
                this.targetName = 'SET_EMAILLISTOUTTAB'
            }else  if(this.name=='emailListPendingTab'){//待处理
                this.targetName = 'SET_EMAILLISTPENDINGTAB'
            }else  if(this.name=='emailListCustomerTab'){//客户模式
                this.targetName = 'SET_EMAILLISTCUSTOMERTAB'
            }
        },
        methods: {
            toggle(type) {
                this.currentFrag = type;
                this.handleCurrent(1);
                this.filterPosition()
            },
            filterPosition() {
                let left = 0;
                switch (this.currentFrag) {
                    case -1:
                        left = 22;
                        break;
                    case 0:
                        left = 187;
                        break;
                    case 1:
                        left = 342;
                        break;
                    default:
                        break;
                }
                this.Left = left + 'px'
            },
            lookFixed() {
                this.isFixed = this.isFixed == 1 ? 0 : 1;
                this.handleCurrent(1)
            },
            //固定
            fixedTop(temailInfoId, type) {
                fixTop(temailInfoId, type).then(res => {
                    this.dealResult(res, 1)
                })
            },
            //设为完成
            toComplete(tEmailInfoId) {
                this.$confirm('将该邮件标记为已完成状态吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    completeEmail({temailInfoIds: [tEmailInfoId]}).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    });
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.size = val;
                this.handleCurrent(1)
            },
            handleCurrent(val) {
                this.currentPage = val;
                this.getData();
            },
            //根据邮箱+类型获取对应的邮件列表数据
            getData() {
                console.log(this.id);
                this.loading=true;
                const params = {
                    emailType: this.currentFrag == -1 ? '' : this.currentFrag,//0已发送 1 收件 ‘’ 全部
                    allEmailList: [this.id],
                    current: this.currentPage,
                    size: this.size
                }
                relationEmail(params).then(res => {
                    this.loading=false;
                    if (res.data.success) {
                        const result = res.data.data;
                        const list = result.records;
                        this.data = [];
                        if(this.currentPage==1){
                            this.total = result.total;
                        }
                        this.listAll = list;
                        let today = [], yesterday = [], nowWeek = [], month = [], previous = [];
                        let weekT = getNowWeek();
                        let monthT = getNowMonth();
                        let todayTime = getToady(),//今天
                            yesterdayTime = getYesterday(),//昨天
                            weekStartTime = weekT.startDate,
                            monthStartTime = monthT.startDate,
                            monthEndTime = monthT.endDate;
                        list.forEach((item, index) => { //sendTime
                            const time = new Date(item.sendTime).getTime();
                            // 判断是否是  更早
                            if (todayTime <= time) { //今天
                                today.push(item);
                            } else if ((yesterdayTime <= time) && (time < todayTime)) {//昨天
                                yesterday.push(item);
                            } else if ((weekStartTime < time) && (time < yesterdayTime)) {//本周
                                nowWeek.push(item);
                            } else if ((monthStartTime < time) && (time < monthEndTime)) {//本月
                                month.push(item);
                            } else if (time < monthStartTime) {//更早
                                previous.push(item);
                            }
                        })
                        //插入数组
                        this.data.push({title: '今天', list: today, total: `${today.length}`})
                        this.data.push({title: '昨天', list: yesterday, total: `${yesterday.length}`})
                        this.data.push({title: '本周', list: nowWeek, total: `${nowWeek.length}`})
                        this.data.push({title: '本月', list: month, total: `${month.length}`})
                        this.data.push({title: '更早', list: previous, total: `${previous.length}`})
                    }
                }).catch(err => {
                    this.loading=false;
                })
            },
            //去除标记 单个
            handleClose(id) {
                delLabel(id).then(res => {
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            //去详情页面
            toDetail(row) {
                this.$store.commit('SET_EMAILPAGE', this.currentPage)
                this.$store.commit('SET_EMAILPAGESIZE', this.size)
                //新增组件
                const ID = row.temailInfoId + "R";//row.id - 临时
                if (getDiffList(ID,this.name)== -1) {
                    this.$store.commit(this.targetName, {
                        type: 1, row: {
                            id: ID,
                            title: row.emailSubject,
                            state: 1,
                            close: true
                        }
                    })
                } else {
                    this.$store.commit(this.targetName, {type: 0, current: ID})
                }

            },
            //标记为待办
            toTimeDeal(id, processTime) {
                this.$refs.timeDialog.init(id, processTime);
                this.dialogTime = true;
            },
            //稍后处理
            toNextDeal() {
                if (!this.getSelectList()) {
                    this.targetTime = '';
                    return;
                }
                if (this.targetTime == '稍后处理') {
                    this.dialogVisible = true;
                } else {
                    this.submitTime()
                }
            },
            submitTime() {
                const time = this.getTime();
                if (time.indexOf('NaN') != -1) {//，没找到
                    this.$message({
                        type: "success",
                        message: '请选择自定义时间'
                    });
                    return;
                }
                this.targetTime = '';
                this.nextTime = '';
                this.dialogVisible = false;
                nextEmail({
                    processTime: time,
                    temailInfoIds: this.tEmailInfoIds
                }).then(res => {
                    this.dealResult(res, 1)
                    this.bus.$emit('refreshEmailNum')
                }).catch(err => {
                    console.log(err)
                });
            },
            getTime() {
                switch (this.targetTime) {
                    case '1':
                        return getDate(0) + " " + this.todayTime + ":00";
                    case '2':
                        return getDate(1) + " 08:00:00";
                    case '3':
                        return getDate(2) + " 08:00:00";
                    case '4'://下周
                        let result;
                        if (this.nextWeek == '一') {
                            result = getNext(1)
                        } else if (this.nextWeek == '二') {
                            result = getNext(2)
                        } else if (this.nextWeek == '三') {
                            result = getNext(3)
                        }
                        return result + " 08:00:00";
                    case '稍后处理':
                        return this.nextTime;
                    default:
                        return
                }
            },
            newLabel() {
                var labelID = this.common.labelList[0].id
                labelEmail({
                    tagId: labelID,
                    temailInfoIds: this.tEmailInfoIds
                }).then(res => {
                    this.dialogTime = false;
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            //删除邮件
            delEmail(id) {
                this.$confirm('是否删除选中邮件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    //获取选中的邮件列表
                    delEmail([id]).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                });
            },
            dealResult(res, index) {
                if (res.data.success) {
                    this.checked = false;
                    this.targetRemove = this.targetLabel = '';
                    this.tEmailInfoIds = [];
                    this.bus.$emit('refreshEmailNum')
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                    let page = index ? this.currentPage : 1;
                    this.handleCurrent(page);
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }
            },
            cancel() {
                this.dialogVisible = false;
                this.nextTime = '';
                this.targetTime = ''
            },
            filterEmail(row, state) {
                return row.senderEmail;
                const type = row.emailCustomerVO.type;
                if (type != 0) {
                    let str = row.emailCustomerVO.contactName + " | " + row.emailCustomerVO.enterpriseName;
                    return state ? str + row.emailCustomerVO.email : str;
                }
                let name='',email='';
                if (parseInt(row.emailType)) {//收件箱
                    name = row.senderNickName;
                    email = row.senderEmail;
                }else{//已发送
                    //处理多个收件人情况
                    email = row.addresseeEmail.split(',')[0];
                }
                let str = '';
                if (name) {
                    if (name.indexOf("@") != -1) {
                        return name.split("@")[0] + " | " + email
                    }
                    str = name + " | " + email
                } else {
                    str = email.split("@")[0] + " | " + email
                }
                return str;
            }
        },
    }
</script>

<style scoped lang="scss">
  @import "../../../styles/email";
  img.icon-frag {
    width: 16px;
    vertical-align: middle;
  }
</style>
